# coding=utf-8

#http://blog.csdn.net/fgf00/article/details/52872730
#install
# sudo apt install rabbitmq-server
#start web management
# http://blog.csdn.net/joyhen/article/details/73136092
# rabbitmq-plugins.bat enable rabbitmq_management
#configure
# http://127.0.0.1:15672  guest/guest
import pika
import time

class MQ:
    connection = None
    channel = None
    def __init__(self,ip):
        # 建立实例
        creds_broker = pika.PlainCredentials("guest", "guest")
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(ip,5672,virtual_host="/",credentials=creds_broker))
        # 声明管道
        self.channel = self.connection.channel()

    def declare_queue(self,name='test_queue'):
        # 在管道里声明queue
        self.channel.queue_declare(queue=name)

    def __del__(self):
        self.connection.close()  # 队列关闭


class Consumer(MQ):
    def __init__(self,ip='127.0.0.1'):
        MQ.__init__(self,ip)

    @staticmethod
    def callback(channel, method, properties, body):  # 四个参数为标准格式
        print(channel, method, properties)  # 打印看一下是什么
        # 管道内存对象  内容相关信息  后面讲
        print(" [x] Received %r" % body)


    def run(self,queue_name,callback=callback):
        self.channel.basic_qos(prefetch_count=1)
        self.channel.basic_consume(  # 消费消息
                callback,  # 如果收到消息，就调用callback函数来处理消息
                queue=queue_name,  # 你要从那个队列里收消息
                # no_ack=True  # 写的话，如果接收消息，机器宕机消息就丢了
                # 一般不写。宕机则生产者检测到发给其他消费者
                )

        print(' [*] Waiting for messages. To exit press CTRL+C')
        self.channel.start_consuming()  # 开始消费消息

    def __del__(self):
        pass


class Producer(MQ):

    def __init__(self,ip='127.0.0.1'):
        MQ.__init__(self,ip)


    def send(self,queue_name,message):
        # RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
        self.channel.basic_publish(exchange='',
                              routing_key=queue_name,  # queue名字
                              body=message)  # 消息内容

    def __del__(self):
        pass



if __name__ == '__main__':
    p = Producer()
    p.declare_queue("test_queue")
    p.send("test_queue","abcdef")
    p.send("test_queue", "abcdef")
    p.send("test_queue", "abcdef")
    p.send("test_queue","abcdef")
    p.send("test_queue", "abcdef")


    def callback(channel, method, properties, body):  # 四个参数为标准格式
        #print(channel, method, properties)  # 打印看一下是什么
        # 管道内存对象  内容相关信息  后面讲
        print(" [x] Received %r" % body)
        time.sleep(15)
        channel.basic_ack(delivery_tag = method.delivery_tag)  # 告诉生成者，消息处理完成
    c = Consumer()
    c.declare_queue("test_queue")
    c.run("test_queue",callback=callback)

